package com.idcheck.rechcustoms;

import android.annotation.SuppressLint;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;

import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Bundle;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import com.idcheck.rechcustoms.ScreenOffAdminReceiver;

import utils.AndroidRootUtils;
import utils.OtherUtil;
import utils.PrefUtils;

import android.content.Context;
import android.os.PowerManager;
import android.os.SystemClock;
import utils.LogUtil;
//import com.rech.utils.OtherUtil;
import utils.TimeUtils;
import utils.TimerTaskUtil;
import com.idcheck.rechcustoms.websocket.*;

import io.reactivex.disposables.Disposable;
//测试手机号15959220396 密码123456
/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    private CountDownTimer mTimer=null; //UI计时

    private TextView lanzhengbtn;
    private TextView selfbtn;
    private TextView sendbtn;



    public static String apicabinetId;
    public static String apiwebsocketId;
    private String strPassword="";
    private volatile long resetTimeStamp = 0;
    private volatile long brightTimeStamp = 0;
    private volatile long mCountSetting = 0;
    private volatile long countTimeStamp = 0;
    private int adminId = 0;
    private String adminTel = "";
    private int companySeqId = 0;
    private Disposable timedTask;
//    PowerManager pm;
//    PowerManager.WakeLock wakeLock = null;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;


    private boolean mVisible;
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    private boolean isLanzheng = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);
        mVisible = true;
        if(getSupportActionBar()!=null){

            getSupportActionBar().hide();

        }
        hideBottomUIMenu();
        Log.d("TAG brightness: ",String.valueOf(getScreenBrightness(this.getApplicationContext())));

        SharedPreferences sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);

// 读取不同类型的值
        apicabinetId = sharedPreferences.getString("cabinetId", "0");
        apiwebsocketId = sharedPreferences.getString("websocketId", "0");

        if(apicabinetId.equals("0"))
        {
            Intent intent = new Intent();
            intent = new Intent(FullscreenActivity.this, SettingActivity.class);
            startActivity(intent);
            return ;
        }

//        pm = (PowerManager) getApplication().getSystemService(Context.POWER_SERVICE);
//        wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
//                | PowerManager.SCREEN_DIM_WAKE_LOCK, "rech-custom");

        lanzhengbtn = findViewById(R.id.lanzhengbtn);
        selfbtn = findViewById(R.id.selfbtn);
        sendbtn = findViewById(R.id.sendbtn);
        //相对字体大小
        SpannableString spRelativeSize1 = new SpannableString("存证\n(管理员)");
        RelativeSizeSpan relativeSizeSpan1 = new RelativeSizeSpan((0.5f));
        spRelativeSize1.setSpan(relativeSizeSpan1, 2, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        sendbtn.setText(spRelativeSize1);


        SpannableString spRelativeSize2 = new SpannableString("查收资料\n(管理员)");
        RelativeSizeSpan relativeSizeSpan2 = new RelativeSizeSpan((0.5f));
        spRelativeSize2.setSpan(relativeSizeSpan2, 4, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        lanzhengbtn.setText(spRelativeSize2);

//






        initTimer();

        //eventbus
        initView();




        findViewById(R.id.selfbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent = new Intent(FullscreenActivity.this, ChooseActivity.class);
                startActivity(intent);
                resetTimeStamp = System.currentTimeMillis();

            }
        });

        findViewById(R.id.recvbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent = new Intent(FullscreenActivity.this, QuZhengActivity.class);
                startActivity(intent);

            }
        });

        findViewById(R.id.sendbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent = new Intent(FullscreenActivity.this, AdminCunZhengLoginActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.lanzhengbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent = new Intent(FullscreenActivity.this, AdminChaShouZiLiaoLoginActivity.class);
                startActivity(intent);
            }
        });

        findViewById(R.id.textWeek).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCountSetting ++;
                countTimeStamp = System.currentTimeMillis();

                if(mCountSetting > 4){
//                    findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                    findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                    findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                    findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                    Intent intent = new Intent();
                    intent = new Intent(FullscreenActivity.this, SettingActivity.class);
                    startActivity(intent);
                    resetTimeStamp = System.currentTimeMillis();
                    mCountSetting = 0;
                }
            }
        });
        findViewById(R.id.textDate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCountSetting ++;
                countTimeStamp = System.currentTimeMillis();

                if(mCountSetting > 4){
//                    findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                    findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                    findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
//                    findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                    Intent intent = new Intent();
                    intent = new Intent(FullscreenActivity.this, AdminForInternalLoginActivity.class);
                    startActivity(intent);
                    resetTimeStamp = System.currentTimeMillis();
                    mCountSetting = 0;
                }
            }
        });

        findViewById(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Date date = new Date(System.currentTimeMillis());
                int hours = date.getHours();
                int minutes = date.getMinutes();
                int seconds = date.getSeconds();
                if(hours > 21 || hours < 7){
                    brightTimeStamp =  System.currentTimeMillis();
                    setAppScreenBrightness(200);
                }


            }
        });
        setAppScreenBrightness(200);

        if(hasSerialPorts())
        {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SerialPortWorker.serialHelper = new SerialPortHelper();
                    SerialPortWorker.serialHelper.setPort("/dev/ttyS1");
                    try{

                        SerialPortWorker.serialHelper.open();
                        com.idcheck.rechcustoms.websocket.WebSocketClient.connect("121.37.251.46"); // 发起连接 120.77.149.44
                        Log.d("WebSocketClient","发起连接");
                        new SerialPortReadWorker().start();
                        new SerialPortWriteWorker().start();

                    }catch (Exception e){
                        e.printStackTrace();
                        finish();
                    }
                }
            }).start();

            startTimeTask();
        }

    }

    //ADD
    private synchronized void startTimeTask() {
        TimerTaskUtil.timedTask(new TimerTaskUtil.TimerTasklenster() {
            @Override
            public void onNext() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        com.idcheck.rechcustoms.websocket.WebSocketClient.Send(apiwebsocketId);
                        Log.d("WebSocketClient","发送数据："+apiwebsocketId);
                    }
                }).start();
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                timedTask = disposable;
            }

            @Override
            public void onError() {

            }

            @Override
            public void onComplete() {
                startTimeTask();

            }
        }, 1);
    }
    //ADD
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay

    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unInitTimer();
    }
    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (99999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!FullscreenActivity.this.isFinishing()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 \n HH:mm:ss");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        TextView datetext = (TextView)findViewById(R.id.textDate);
                        datetext.setText(simpleDateFormat.format(date));
                        TextView weektext = (TextView)findViewById(R.id.textWeek);
                        weektext.setText(getWeek());
                        if(resetTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - resetTimeStamp;
                            if(timeOut > 180000){
                                resetView();
                            }
                        }
                        if(brightTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - brightTimeStamp;
                            if(timeOut > 3600000){
                                int hours = date.getHours();
                                int minutes = date.getMinutes();
                                int seconds = date.getSeconds();
                                if(hours > 19 || hours < 7){
                                    brightTimeStamp =  System.currentTimeMillis();
                                    setAppScreenBrightness(100);
                                }
                                brightTimeStamp = 0;
                            }
                        }

                        if(countTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - countTimeStamp;
                            if(timeOut > 3000){
                                mCountSetting = 0;
                                countTimeStamp = 0;
                            }
                        }

                        int hours = date.getHours();
                        int minutes = date.getMinutes();
                        int seconds = date.getSeconds();
                        if(hours == 6 && minutes == 0 && seconds < 10){
                            setAppScreenBrightness(200);
                        }
                        if(hours == 22 && minutes == 0 && seconds < 10){
                            setAppScreenBrightness(100);
                        }

                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public static String getWeek(){
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }


    private void EventMessageForWait(){
        Toast.makeText(FullscreenActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
    }
    private void EventMessageForError(int what){
        switch(what){
            case 1101:
                Toast.makeText(FullscreenActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                break;
            case 1301:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                resetView();
                break;
            case 1401:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                resetView();
                break;
            case 1501:
                Toast.makeText(FullscreenActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;
            case 1701:
                Toast.makeText(FullscreenActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;

        }
    }
    private void initView(){

        this.resetTimeStamp = 0;
        this.brightTimeStamp = 0;
        this.mCountSetting = 0;
        this.countTimeStamp = 0;
        this.adminId = 0;
        this.adminTel = "";
        this.companySeqId = 0;

        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }
    private boolean hasSerialPorts() {
        if(apicabinetId.equals("1"))
        {
            return false;
        }
        return true;
    }
    private void resetView(){

        findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));

        this.resetTimeStamp = 0;
        this.brightTimeStamp = 0;
        this.mCountSetting = 0;
        this.countTimeStamp = 0;
        this.adminId = 0;
        this.adminTel = "";
        this.companySeqId = 0;

        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        restartApplication();
    }
    private void resetViewMessage(){
        ;
    }
    private void EventMessageForSaveOpen(Object obj){
        try{
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }else{
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.error);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("请检查网络");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }
    }

    private void EventMessageForSend(Object obj){
        try{
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);

            }else{

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.warning);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);

            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("网络错误");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }
    }
    private void EventMessageForCompany(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//                companyId.setEnabled(true);
//                companyId.setText("");
//                companyId.requestFocus();
                String val = result.getJSONObject("data").getString("companyname");
                adminTel = result.getJSONObject("data").getString("contact");
                companySeqId = result.getJSONObject("data").getInt("companyid");
//                companyName.setText(val);
//                companyName.setTextColor(Color.BLACK);
                findViewById(R.id.sendsubmit).setEnabled(true);
                resetTimeStamp = System.currentTimeMillis();
            }else{
                ;
                //Toast.makeText(FullscreenActivity.this,result.getJSONObject("data").getString("msg"),Toast.LENGTH_LONG);
//                companyName.setText(result.getString("msg"));
//                companyName.setTextColor(Color.RED);
                //resetView();
            }

        }catch(Exception e){
            resetView();
        }
    }
    private void EventMessageForAuth(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                PrefUtils.setString(this, "adminid", result.getJSONObject("data").getString("id"));
                if (isLanzheng){
                    startActivity(new Intent(FullscreenActivity.this, GridListActivity.class));
                    isLanzheng = false;
                } else {
                    startActivity(new Intent(FullscreenActivity.this, ChooseCunZhengTypeActivity.class));
                }

            }else{
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 5000);
                //Toast.makeText(FullscreenActivity.this,result.getString("msg"),Toast.LENGTH_LONG);
            }

        }catch(Exception e){
            resetView();
        }
    }
    private void EventMessageForOpenGrid(Object obj){

        try{
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }else{
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.error);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("请检查网络");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }

    }
    private int getScreenBrightness(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        int defVal = 125;
        return Settings.System.getInt(contentResolver,
                Settings.System.SCREEN_BRIGHTNESS, defVal);
    }
    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    private void setAppScreenBrightness(int birghtessValue) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = birghtessValue / 255.0f;
        window.setAttributes(lp);
    }

}

